#!/usr/bin/env python
#
# Copyright 2006 Bret Taylor
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""Usage: %s

Checks all of the Indie files from this test directory using the compiler
in ../src/indie. We look for comments of the form

    // ERROR: ...

and verify that the Indie compiler reports the same number of errors as
there are ERROR comments in each Indie file.
"""

__author__ = 'Bret Taylor <btaylor@gmail.com>'

import re
import os
import os.path
import sys

_INDIE_COMMAND = "%s --check%s %s"
_SYSTEM_FLAGS= " --very-quiet"

def main(argv):
    if len(argv) != 1:
        print >> sys.stderr, __doc__ % argv[0]
        return 1
    executable = os.path.dirname(os.path.dirname(__file__)) + "/src/indie"
    if not os.access(executable, os.F_OK):
        print >> sys.stderr, "Could not find the compiler at '%s'" % executable
        print >> sys.stderr, "Are you sure the compiler has been built " \
                             "properly?"
        return 1
    if not run_tests(executable, os.path.dirname(__file__)):
        return 2


def run_tests(indie_path, test_dir):
    no_errors = True
    for dirpath, dirs, files in os.walk(test_dir):
        for filepath in files:
            if not filepath.endswith(".indie"): continue
            path = os.path.join(dirpath, filepath)

            file = open(path, "r")
            errors = re.findall("// ERROR", file.read())
            file.close()
            expected = len(errors)

            print _INDIE_COMMAND % (indie_path, "", path)
            command = _INDIE_COMMAND % (indie_path, _SYSTEM_FLAGS, path)
            sys.stdout.write("    %d error(s) expected: " % expected)

            result = os.system(command) / 256
            if result == expected:
                print "VERIFIED"
            else:
                no_errors = False
                print "FAILED"
                print "    Indie compiler reported %d error(s)" % result

    return no_errors


if __name__ == '__main__':
    sys.exit(main(sys.argv))
